#!/usr/bin/python3
# vim: set fileencoding:utf-8
import os
import sys
import yaml
import ping
from git.repo import Repo
from git import RemoteProgress
import time
import readfile

scale = 20
start = time.perf_counter()


class CloneProgress(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=""):
        if message:
            i = int(cur_count * scale / max_count)
            a = "*" * i
            b = "." * (scale - i)
            c = (i / scale) * 100
            dur = time.perf_counter() - start
            print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c, a, b, dur), end="")
            # if(c==100):
            # print("")
            time.sleep(0.1)


# 获取yaml文件路径
yamlPath = os.path.join(os.path.expanduser("~"), ".config/center.yml")

if not os.path.exists(yamlPath):
    yamlPath = os.path.join("center.yml")

# open方法打开直接读出来
f = open(yamlPath, "r", encoding="utf-8")
cfg = f.read()

params = yaml.load(cfg, Loader=yaml.SafeLoader)
for ele in params:
    if (len(sys.argv) > 1 and "push" == sys.argv[1]) and "yapai" != ele.split("/")[-1]:
        print("follow project will do push operation , be careful")
    folder_name = os.path.join(os.path.expanduser("~"), ele)
    if os.path.exists(folder_name):
        print(folder_name + ":exit")
    else:
        print(folder_name + ":noexit")
        os.makedirs(folder_name)
    print("\033[1;33m start clone into {} now ....\033[0m".format(folder_name))
    branch_ele = params[ele]
    for branch_name in branch_ele:
        print("branch=" + branch_name)
        url_list = branch_ele[branch_name].split(" ")
        for url in url_list:
            sub_path = ""
            if url.find("https://") != -1:
                sub_path = url.split("https://")[1]
            if url.find("git@") != -1:
                sub_path = url.split("git@")[1]
            clear_project_path = sub_path.split("/")[0]
            ping_result = False
            for ping_index in range(0, 5):
                result = ping.pingtelnet(clear_project_path)
                if result is False:
                    time.sleep(1)
                else:
                    ping_result = True
                    break
                # True 表示服务正常
            if ping_result is False:
                print(url + "ping failed , do not git operation")
                continue
            print("url=" + url)
            project_name = url.split("/")[-1].split(".")[0]
            download_path = os.path.join(folder_name, project_name)
            print("download_path=" + download_path)
            try:
                repo = Repo(download_path)
                files = repo.untracked_files
                for file in files:
                    if "yapai" != ele.split("/")[-1]:
                        repo.git.add(file)
                if repo.is_dirty():
                    idea_file = os.path.join(
                        folder_name, project_name + "/.idea/workspace.xml"
                    )
                    if os.path.exists(idea_file):
                        need_staging_files = readfile.get_staging_files(idea_file)
                        print(need_staging_files)
                        for nsf in need_staging_files:
                            print(nsf)
                            print("stage file={}".format(nsf))
                            if "yapai" != ele.split("/")[-1]:
                                repo.git.add(nsf)
                        if (
                            len(need_staging_files) > 0
                            and "yapai" != ele.split("/")[-1]
                        ):
                            repo.git.commit(
                                "-m",
                                "stage chard {} files ".format(len(need_staging_files)),
                            )
                    else:
                        print("checked unstage file , i am staging ....")
                        repo.git.add(".")
                        repo.git.commit("-m", "stage local files")
            except Exception as e:
                print(e)
                print("repository invliad error ...")
                flag = False
                for ix in range(1, 10):
                    try:
                        Repo.clone_from(
                            url,
                            to_path=download_path,
                            branch=branch_name,
                            progress=CloneProgress(),
                        )
                        repo = Repo(download_path)
                        flag = False
                    except Exception as se:
                        flag = True
                    if flag is False:
                        break
                    print("clone error , now start retry....")
                    time.sleep(1)  # 休眠1秒
                print("")
            try:
                repo.git.pull()
                if (
                    len(sys.argv) > 1 and "push" == sys.argv[1]
                ) and "yapai" != ele.split("/")[-1]:
                    repo.git.push()
            except Exception as e:
                print(e)
                print("pull error maybe conflict...")
                tree = repo.git.execute(
                    ["git", "diff", "--name-only", "--diff-filter=U"]
                )
                print("\033[4;31;43mmerge_file=" + tree + "\033[0m")
